<template>
  <BasicTable @register="registerTable">
    <template #tableTitle>
      <div class="ant-btn-groups">
        <a-button type="primary" @click="handleAllocation" v-if="checkAuth('POST-ALLOCATION')">
          分配
        </a-button>
        <a-button type="error" ghost @click="handleDeleteAll" v-if="checkAuth('DELETE-MUlTIPLE')">
          删除
        </a-button></div
      >
    </template>
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'action'">
        <TableAction
          :actions="[
            {
              ifShow: checkAuth('POST-WATCH-INFO'),
              label: '查看',
              onClick: handleAuth.bind(null, record, 'view'),
            },
            {
              ifShow: checkAuth('POST-EDIT'),
              label: '编辑',
              onClick: handleAuth.bind(null, record, 'edit'),
            },
            {
              ifShow: checkAuth('POST-DELETE'),
              label: '删除',
              onClick: handleDelete.bind(null, record),
            },
          ]"
        />
      </template>
    </template>
  </BasicTable>
  <div class="set-page" v-if="isAllocation">
    <DeptTree class="deptTree" @select="handleSelect" ref="deptTreeRef" />
    <PostSetting
      ref="PostSettingRef"
      v-model:value="isAllocation"
      :authType="authType"
      :selectDeptText="selectDeptText"
      :selectDeptId="selectDeptId"
      :selectDeptUserData="selectDeptUserData"
    />
  </div>
</template>
<script lang="ts" setup>
  import { ref, nextTick } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import DeptTree from './DeptTree.vue';
  import PostSetting from './PostSetting.vue';

  import { getUserDeptPostPage } from '/@/api/admin/userDept';
  import { columns, searchFormSchema } from './postAllot.data';
  import {
    getJobConfigurationInformation,
    deleteUserDeptPost,
    batchDel,
  } from '/@/api/admin/userDept';

  import { useMessage } from '/@/hooks/web/useMessage';

  import { setTableEmptyHeight } from '/@/utils';
  import { getBtnAuth, checkAuth } from '/@/utils/cutomPageBtnAuth/index';
  import { useRoute } from 'vue-router';

  const isAllocation = ref<boolean>(false);
  const selectDeptText = ref<string>('');
  const selectDeptId = ref<string>('');
  const selectDeptUserData = ref<Array<any>>([]);
  const PostSettingRef = ref();
  const deptTreeRef = ref();
  const authType = ref<string>('');
  const route = useRoute();

  const { createMessage, createConfirm } = useMessage();

  const [registerTable, { reload, getRowSelection }] = useTable({
    api: getUserDeptPostPage,
    columns,
    formConfig: {
      labelWidth: 75,
      schemas: searchFormSchema,
    },
    rowKey: ({ deptId, postId }) => `${deptId}-${postId}`,
    rowSelection: {
      type: 'checkbox',
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    // showIndexColumn: false,
    actionColumn: {
      width: 160,
      title: '操作',
      dataIndex: 'action',
      // slots: { customRender: 'action' },
      fixed: 'right',
    },
    indexColumnProps: {
      width: 250,
      align: 'left',
    },
    afterFetch(res) {
      setTableEmptyHeight(res);
    },
  });
  getBtnAuth(route, reload);
  function commonOpen(type) {
    isAllocation.value = true;
    authType.value = type;
    nextTick(() => {
      (document.querySelector('.set-page') as HTMLElement).style.height =
        (document.querySelector('.vben-layout-content') as HTMLElement).offsetHeight + 'px';
    });
  }

  async function handleDelete({ deptId, postId, deptName, postName }) {
    createConfirm({
      iconType: 'warning',
      title: '删除提示',
      content: `对${deptName}岗位进行删除，并将${postName}下的成员全 部删除，确认要删除吗？`,
      onOk: async () => {
        await deleteUserDeptPost(deptId, postId);
        createMessage.success('操作成功');
        reload();
      },
    });
  }

  function handleDeleteAll() {
    const keys: any = getRowSelection().selectedRowKeys;
    if (!keys.length) {
      createMessage.error('请先勾选数据！');
    } else {
      createConfirm({
        iconType: 'warning',
        title: '删除提示',
        content: `已选中${keys.length}个岗位进行删除，并将组织部门下的成员全部删除，确认要删除吗？`,
        onOk: async () => {
          const params = keys.map((item) => ({
            deptId: item.split('-')[0],
            postId: item.split('-')[1],
          }));
          await batchDel(params);
          createMessage.success('操作成功');
          reload();
        },
      });
    }
  }

  function handleAllocation() {
    commonOpen('add');
    selectDeptId.value = '';
  }

  function handleAuth(record, type) {
    commonOpen(type);
    nextTick(() => {
      deptTreeRef.value.handleSetSelectData(record.deptId);
    });
  }

  function findItem(val, data, number: any[] = [], name = '') {
    data.forEach((item, index) => {
      if (index !== 0 && number.length > 1 && name !== number[number.length - 1]) {
        number.pop();
      }
      if (item.id !== val) {
        if (item.children) {
          // 这一级id不相等且还有子集，传入子集和拼接好路径继续递归
          number.push(item.name);
          findItem(val, item.children, number, item.name);
        }
        // 判断当前子集是否走到最后一次判断了，如果是最后一个判断那就意味着对比完了也没找到，意味着
        // number保存的最后一个路径中没有要找的值，所以删除最后一个
        if (data.length === index + 1) {
          number.pop();
        }
      } else {
        //   id比对成功
        number.push(item.name);
        throw number;
      }
    });
  }

  async function handleSelect(val, treeData) {
    selectDeptId.value = val;
    PostSettingRef.value.postList.forEach((item) => {
      item.userList = [];
    });
    if (val || val === 0) {
      const res = await getJobConfigurationInformation(val);
      selectDeptUserData.value = res;
      try {
        findItem(val, treeData);
      } catch (res: any) {
        selectDeptText.value = res.join(' - ');
      }
    }
  }
</script>

<style scoped lang="less">
  .deptTree {
    height: 100%;
    width: 248px;
    background-color: #fcfcfc;
    padding: 10px 12px 12px 12px;
    border-right: 1px solid #e9e9e9;
  }

  .set-page {
    display: flex;
    width: 100%;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 999;
  }

  :deep(.ant-btn-groups) {
    .ant-btn {
      margin-right: 16px;
      border-radius: 4px;
    }
  }

  :deep(.ant-table-wrapper) {
    padding-left: 16px !important;
    padding-top: 16px !important;
  }

  :deep(.ant-table-container) {
    padding-top: 8px !important;
  }
</style>
